'use strict';

const Controller = require('egg').Controller;

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

class LoginController extends Controller {
  // 验证码
  async getPhoneCode() {
    const { ctx } = this;
    const str = getRandomInt(1000, 9999).toString();
    ctx.session.code = str;
    ctx.body = {
      code: 0,
      message: 'success',
      data: str,
    };
    console.log(ctx.session);
  }
  // 登录
  async login() {
    const { ctx, app } = this;
    const { username, password, code } = ctx.request.body;
    // 验证用户是否存在
    const users = await app.model.User.findOne({ where: { username } });
    const user = JSON.parse(JSON.stringify(users));
    const token = app.jwt.sign({
      user,
    }, app.config.jwt.secret);
    ctx.validate({
      username: { type: 'string', required: true, desc: '用户名' },
      password: { type: 'string', required: true, desc: '密码' },
    });
    if (Number(code) === ctx.session.code) {
      ctx.body = { data: code, message: '验证码不正确' };
      return;
    }
    if (!user) {
      ctx.body = { data: '', message: '用户不存在' };
      return;
    }
    // 校验密码是否正确
    if (user.password !== password) {
      ctx.body = { data: '', message: '密码不正确' };
      return;
    }
    // 加入session/缓存中
    ctx.session.userToken = token;
    ctx.session.userInfo = user;
    ctx.body = {
      token,
      user,
      message: '登录成功',
      code: 0,
    };
  }

  async logout() {
    const { ctx } = this;
    ctx.session = null;
    ctx.body = { data: [], message: '注销成功', code: 0 };
  }

}

module.exports = LoginController;
